import os
import re
import logging
import pandas as pd
from pathlib import Path
from pandas import DataFrame
from pandas import Series
from dataset.database import Database
from spire.doc import *
from spire.doc.common import *

logging.basicConfig(
    level=logging.DEBUG,
    format='%(levelname)8s: %(message)s'
)


def get_filenames_in_folder_with_check(folder_path: str, file_types: [], format_pattern: str) -> Series:
    filenames = get_filenames_in_folder(folder_path, file_types)
    check_filenames_duplicates(filenames)
    check_filenames_format(filenames, format_pattern)
    return filenames


def get_filenames_in_folder(folder_path: str, file_types: []) -> Series:
    try:
        # 验证文件夹是否存在
        if not os.path.isdir(folder_path):
            logging.error(f"❌ 获取 {folder_path} 下的文件名列表时出错:")
            logging.error(f"  文件夹 {folder_path} 不存在")
            exit(0)

        folder = Path(folder_path)
        matched_files = []
        file_types = [ext.lower() for ext in file_types]  # 统一小写处理

        # 收集所有匹配的文件
        for item in folder.iterdir():
            if item.is_file() and item.suffix.lower() in file_types:
                # 根据返回类型处理路径
                matched_files.append(item.name)

        # 按文件名排序
        matched_files.sort()

        logging.debug(f"在 {folder_path} 中找到 {len(matched_files)} 个 {file_types} 文件")
        filenames = pd.Series(matched_files, name='文件名')

        return filenames
    except Exception as e:
        logging.error(f"❌ 获取 {folder_path} 下的文件名列表时出错:")
        logging.error(f"  {str(e)}")
        exit(0)


def check_filenames_format(filenames: Series, pattern: str):
    logging.debug("检查文件名是否符合规则")
    invalid_strings = []
    for s in filenames:
        if ' ' in s:
            invalid_strings.append(s)
            continue
        match = __match_pattern(s, pattern)
        if match is False:
            invalid_strings.append(s)

    if invalid_strings:
        logging.debug("以下字符串不符合格式要求:")
        for s in invalid_strings:
            logging.debug(f"  - {s}")
        logging.error(f"\n❌ 总计: {len(invalid_strings)} 个字符串不符合规则")
        exit(0)
    else:
        logging.info("✅ 所有文件名都符合格式要求!")


def check_filenames_duplicates(filenames: Series):
    logging.info('检查文件名是否有重复')
    # 去掉后缀再判断重复
    new_se = filenames.str.rsplit('.', n=2).str[0]

    # 计算每个值的出现次数
    value_counts = new_se.value_counts()

    # 找出重复项（出现次数大于1）
    duplicates = value_counts[value_counts > 1]

    if not duplicates.empty:
        logging.info(f"列表中有 {len(duplicates)} 个重复项:")
        for i, (value, count) in enumerate(duplicates.items(), 1):
            logging.info(f"{i}. {value} (出现次数: {count})")
        logging.error('❌ 文件名有重复')
        exit(0)
    else:
        logging.info('✅ 文件名无重复')


def extract_parts_from_filename(filenames: Series, pattern: str, part_index=1) -> Series:
    if pattern is None or pattern == "":
        logging.error("❌ 参数 pattern 不能为空")
        exit(0)

    # 提取函数
    def extract_part(s):
        match = re.compile(pattern).match(s)
        if match:
            return match.group(part_index)
        return None  # 不符合格式的返回None

        # 应用提取函数并返回Series

    return filenames.apply(extract_part)


def get_文档_页数(base_folder: str, filenames: Series):
    # 1. 拼接完整文件路径（文件夹路径 + 文件名）
    se_full_paths = filenames.apply(lambda name: os.path.join(base_folder, name))

    # 2. 遍历每个路径，调用函数获取页数，生成新的Series
    se_page_counts = se_full_paths.apply(lambda path: __get_word_pages(path))

    return se_page_counts


def __match_pattern(text, pattern):
    return bool(re.match(pattern, text))


def __match_any_pattern(text, patterns):
    for pattern in patterns:
        if __match_pattern(text, pattern):
            return True  # 找到第一个匹配就返回
        # if bool(re.match(pattern, text)):
        #     return True  # 找到第一个匹配就返回
    return False  # 所有模式都不匹配


def __get_word_pages(docx_path: str) -> int:
    # 创建Document对象并加载Word文档
    doc = Document()
    doc.LoadFromFile(docx_path)

    # 通过内置文档属性获取页数
    return doc.BuiltinDocumentProperties.PageCount
